package com.lagou.client;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class HbaseClient {

    private final String tableName="user_relation";
    private final String family="friends";
    Configuration conf=null;
    Connection conn=null;
    HBaseAdmin admin =null;

    @Before
    public void init () throws IOException {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","linux121,linux122");
        conf.set("hbase.zookeeper.property.clientPort","2181");
        conn = ConnectionFactory.createConnection(conf);
    }

    public void destroy(){
        if(admin!=null){
            try {
                admin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(conn !=null){
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建表
     * @throws IOException
     */
    @Test
    public void createTable() throws IOException {
        admin = (HBaseAdmin) conn.getAdmin();
        //创建表描述器
        HTableDescriptor userRelation = new HTableDescriptor(TableName.valueOf(tableName));
        //设置列族描述器
        userRelation.addFamily(new HColumnDescriptor(family));
        userRelation.addCoprocessor("hdfs://linux121:9000/processor/processor.jar|com.lagou.processor.MyProcessor|1001|");
        //执⾏创建操作
        admin.createTable(userRelation);
        System.out.println("user_relation表创建成功！！");

        destroy();
    }

    /**
     * 插⼊⼀条数据
     * @throws IOException
     */
    @Test
    public void putData() throws IOException {
        //获取⼀个表对象
        Table t = conn.getTable(TableName.valueOf(tableName));
        //设定rowkey
        Put put = new Put(Bytes.toBytes("2"));
        //列族，列，value
        put.addColumn(Bytes.toBytes(family), Bytes.toBytes("1"), Bytes.toBytes("1"));
        //执⾏插⼊
        t.put(put);
        // t.put();//可以传⼊list批量插⼊数据
        //关闭table对象
        t.close();
        System.out.println("插⼊成功！！");
    }

    /**
     * 删除⼀条数据
     * @throws IOException
     */
    @Test
    public void deleteData() throws IOException {
        //需要获取⼀个table对象
        final Table userRelation = conn.getTable(TableName.valueOf(tableName));
        //准备delete对象
        final Delete delete = new Delete(Bytes.toBytes("2"));
        delete.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("fid"));//最好使用协处理器实现
        //执⾏删除
        userRelation.delete(delete);
        //关闭table对象
        userRelation.close();
        System.out.println("删除数据成功！！");
    }

}
